/*
 * MenuModelManager.cpp
 *
 *  Created on: Aug 13, 2013
 *      Author: epeterson
 */

#include "MenuModelManager.h"

#include <QDebug>
#include <QDir>
#include <QFileInfo>
#include <QListIterator>
#include <QStringList>
#include <QVariant>
#include <QVariantList>
#include <QVariantMap>

#include <bb/cascades/ItemGrouping>

#include <bb/data/JsonDataAccess>

MenuModelManager::MenuModelManager(QObject * parent): QObject(parent),
	_menuId(""), _menuSource("")
{
	qDebug() << "Hello, world";
	qDebug() << "2 + 2 =" << 5;

	_dataModel.setParent(this);
	_dataModel.setGrouping(bb::cascades::ItemGrouping::None);
	_dataModel.setSortingKeys(QStringList() << "name");

	connect(this, SIGNAL(menuIdChanged(void)), this, SLOT(updateDataModel(void)));
	connect(this, SIGNAL(menuSourceChanged(void)), this, SLOT(updateDataModel(void)));
}

MenuModelManager::~MenuModelManager()
{
}

bb::cascades::DataModel * MenuModelManager::dataModel(void)
{
	return &_dataModel;
}

QString MenuModelManager::menuId(void)
{
	return _menuId;
}

void MenuModelManager::setMenuId(QString menuId)
{
	if (_menuId != menuId)
	{
		_menuId = menuId;
		emit menuIdChanged();
	}
}

QString MenuModelManager::menuSource(void)
{
	return _menuSource;
}

void MenuModelManager::setMenuSource(QString menuSource)
{
	if (_menuSource != menuSource)
	{
		_menuSource = menuSource;
		emit menuSourceChanged();
	}
}

void MenuModelManager::updateDataModel(void)
{
	if (_menuId != "" && _menuSource != "")
	{
		QString path = _menuSource;
		path.replace(QRegExp("^asset:///"), QDir::currentPath() + "/app/native/assets/");

		if (QFileInfo(path).exists())
		{
			bb::data::JsonDataAccess jda;
			QVariant menuData = jda.load(path);

			if (jda.hasError())
			{
				// ERROR
			}

			else
			{
				QVariantMap menu = findMenu(menuData, _menuId);

				if (menu.isEmpty())
				{
					// ERROR
				}

				else
				{
					_dataModel.clear();
					_dataModel.insertList(menu.value("items").toList());
				}
			}
		}

		else
		{
			// ERROR
		}
	}
}

QVariantMap MenuModelManager::findMenu(const QVariant& data, QString menuId)
{
	QVariantMap result;

	if (data.type() == QVariant::Map)
	{
		QVariantMap map = data.toMap();

		if (map.contains("type") && map.value("type").toString() == "menu")
		{
			if (map.contains("id") && map.value("id").toString() == menuId)
			{
				result = map;
			}

			else if (map.contains("items") && map.value("items").type() == QVariant::List)
			{
				QListIterator<QVariant> iterator(map.value("items").toList());

				while (iterator.hasNext())
				{
					QVariantMap item = findMenu(iterator.next(), menuId);

					if (! item.isEmpty())
					{
						result = item;
						break;
					}
				}
			}
		}
	}

	return result;
}
